﻿#region
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ComicsDownloader.Engine;
using ComicsDownloader.Forms;
using ComicsDownloader.Properties;
using HtmlAgilityPack;
using HtmlDocument = HtmlAgilityPack.HtmlDocument;

#endregion

namespace ComicsDownloader.Controls
{
    public partial class PictureListControl : RootControl
    {
        public PictureListControl()
        {
            InitializeComponent();

            _downloadedFont = new Font("Gulim", 9, FontStyle.Strikeout);
        }

        private readonly Font _downloadedFont;

        private DownloadForm _downloadForm;

        public void Initialize(DownloadForm downloadForm)
        {
            _downloadForm = downloadForm;
        }

        public Task<bool> AddRangeAsync(List<Picture> pictures)
        {
            return Task.Factory.StartNew(() => AddRange(pictures));
        }

        public bool  AddRange(List<Picture> pictures)
        {
            List<Task> tasks = new List<Task>();

            Parallel.ForEach(pictures, picture =>
            {
                Task task = Task.Factory.StartNew(() => { Download(picture); });
                tasks.Add(task);
            });

            Task.Factory.ContinueWhenAll(tasks.ToArray(), tasks1 => { });

            return true;
        }

        private void Download(Picture picture)
        {
            _downloadForm.ShowStatus(picture.TitleWithNo);

            WebClient _webClient = new WebClient();

            var html = _webClient.DownloadString(picture.Url);

            string pictureUrl = ExtractPictureUrl(html);

            if (pictureUrl == null)
                return;

            string pathToDownload = Path.Combine(Settings.Default.DownloadRoot, picture.LocalPath);

            var directory = Path.GetDirectoryName(pathToDownload);
            if (Directory.Exists(directory) == false)
                Directory.CreateDirectory(directory);

            _webClient.DownloadFile(pictureUrl, pathToDownload);
            
            picture.Downloaded = true;

            this.InvokeIfNeeded(() =>
                                {
                                    lstList.Items.Add(picture.TitleWithNo);
                                    lstList.SelectedIndex = lstList.Items.Count - 1;
                                });
        }

        private static string ExtractPictureUrl(string html)
        {
            HtmlDocument htmlDocument = new HtmlDocument();
            htmlDocument.Load(new StringReader(html));
            var node = htmlDocument.GetElementbyId("CmAdContent");

            string imageUrl = null;
            foreach (HtmlNode childNode in node.ChildNodes)
            {
                string src = childNode.GetAttributeValue("src", null);
                if (src != null && src.EndsWith(".jpg"))
                {
                    imageUrl = src;
                    break;
                }
            }
            return imageUrl;
        }
    }
}